package com.mdd.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.UserInvitation;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.user.UserInvitationMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IUserInvitationService;
import com.mdd.front.validate.commons.PageValidate;
import com.mdd.common.vo.UserInvitationVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author shenjian
 * @createTime 2023年03月04日 15:58:00
 */
@Service
@Log4j2
public class UserInvitationServiceImpl implements IUserInvitationService {

    @Resource
    UserMapper userMapper;
    @Resource
    UserInvitationMapper userInvitationMapper;

    @Override
    public PageResult<UserInvitationVo> list(PageValidate pageValidate) {
        Integer userId = LikeFrontThreadLocal.getUserId();
        Integer pageNo   = pageValidate.getPageNo();
        Integer pageSize = pageValidate.getPageSize();

        Page<UserInvitationVo> iPage = PageHelper.startPage(pageNo, pageSize).doSelectPage(() ->
                this.userInvitationMapper.getUserInvitationList(userId));
        for (UserInvitationVo invitationVo : iPage.getResult()) {
            invitationVo.setAvatar(UrlUtils.toAbsoluteUrl(invitationVo.getAvatar()));
        }
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getPageNum(), iPage.getPageSize(), iPage.getResult());
    }

    @Override
    public int acceptInvitation(Integer sn, Integer userId) {
        Assert.notNull(sn, "邀请人不能为空");
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("sn", sn)
                .last("limit 1"));
        Assert.notNull(user, "邀请人不存在");
        Assert.isTrue(userId != 0, "请先登录");
        UserInvitation invitation = new UserInvitation();
        invitation.setInviterId(user.getId());
        invitation.setInviteeId(userId);
        invitation.setHasOrder(0);
        invitation.setCreateTime(TimeUtils.timestamp());
        return userInvitationMapper.insert(invitation);
    }
}
